#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cout << argv[0] << " error" << endl;
        exit(1);
    }    
    
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout << "sockfd error" << endl;
        exit(1);
    }

    struct sockaddr_in server;
    server.sin_port = htons(serverport);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(1)
    {
        std::string message;
        cout << "Please enter: ";
        std::getline(std::cin, message);

        int n = sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr*)&server, sizeof(server));
        if(n > 0)
        {
            struct sockaddr_in server;
            socklen_t size = sizeof(server);

            char buffer[1024];
            int m = recvfrom(sockfd, buffer,sizeof(buffer), 0, (sockaddr*)&server, &size);  
            if(m > 0)
            {
                buffer[m] = 0;
                cout << buffer << endl;
            }
            else
            {
                cout << "client recvfrom error" << endl;
                exit(1);
            }
            
        }
        else
        {
            cout << "client sendto error" << endl;
            exit(1);
        }
    }
    close(sockfd);
    return 0;
}